const { Store } = require('koa-session2')
const { Session } = require('./redis')

class RedisStore extends Store {
  // eslint-disable-next-line no-useless-constructor
  constructor() {
    super()
  }

  async get(sid, ctx) {
    const data = await Session.get(sid)
    return JSON.parse(data)
  }

  async set(session, { sid = this.getID(24), maxAge = 1000000 } = {}, ctx) {
    try {
      // Use redis set EX to automatically drop expired sessions
      await Session.set(sid, session, maxAge)
    } catch (e) {}
    return sid
  }

  async destroy(sid, ctx) {
    const redisDel = await Session.del(sid)
    return redisDel
  }
}

module.exports = RedisStore
